//
// Created by andrew on 2024/9/24.
//


#include <string>
#include <vector>
#include <unordered_set>

#include <iostream>
#include <gtest/gtest.h>
#include <climits>

using namespace std;



class Solution {
public:
    int myAtoi(string s) {

        auto len = s.length();
        // 去除空格
        int index = 0;
        while (index < len) {
            if (s[index] != ' ') {
                break;
            }
            index++;
        }

        if (index == len) {return 0;}

        //将前面的正负号取出来
        int sign = 1; // 默认情况下是正数
        if (s[index] == '+') {
            index ++;
        } else if (s[index] == '-') {
            sign = -1;
            index++;
        }

        int res = 0;
        while (index < len) {
            // 每次取出一个字符进行计算
            char curChar = s[index];
            // 若是字符不合法就退出循环,返回上次循环计算的结果
            if (curChar < '0' || curChar > '9') {
                break;
            }
            // 保证res没有溢出的风险
            if (res > INT32_MAX / 10 || (res == INT32_MAX / 10 && (curChar - '0') > INT32_MAX % 10)) {
                return INT32_MAX;
            }

            if (res < INT32_MIN / 10 || (res == INT32_MIN / 10 && (curChar - '0') > -(INT32_MIN % 10))) {
                return INT32_MIN;
            }

            res = res * 10 + sign * (curChar - '0');
            index ++;
        }

        return res;
    }
};



TEST(leetcode8, leetcode) {
    Solution solution;

    EXPECT_EQ(42, solution.myAtoi("42"));


}



